import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Row, Col, Upload, message, Avatar } from 'antd';
import { apiPrefix } from '../../../utils/config';
import { connect } from 'dva';

const PersonalData = ({ userInfo, dispatch }) => {
  const [form] = Form.useForm();
  const [avatar, setAvatar] = useState(); // 存储图片的URL
  const [fileList, setFileList] = useState([]); // 存储上传的文件列表
  const [str, setStr] = useState("上传头像");

  useEffect(() => {
    form.setFieldsValue(userInfo);
    if (userInfo.imgFilePath) {
      setAvatar(apiPrefix + "/" + userInfo.imgFilePath);
    }
  }, [userInfo]);

  const updateUserProfile = (value) => {
    dispatch({
      type: 'personalData/updateUserProfileEffect',
      payload: {
        fileData: fileList.length > 0 ? [fileList[0]] : [],
        ...value,
        userId: userInfo.userId
      }
    });
    setFileList([]);
    setStr("上传头像");
  };

  const beforeUpload = (file) => {
    const reader = new FileReader();
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件！');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!');
      return false;
    }
    // 如果需要的话，可以在这里添加其他逻辑（例如上传前的处理）  
    reader.onload = (e) => {
      setAvatar(e.target.result);
      setStr("点击下方保存修改后生效");
      setFileList([file]); // 将选择的文件添加到fileList中
    };
    reader.readAsDataURL(file);
    return false; // 阻止自动上传
  };

  const handleRemove = () => {
    if (userInfo.imgFilePath) {
      setAvatar(apiPrefix + "/" + userInfo.imgFilePath);
    } else {
      setAvatar();
    }
    setFileList([]);
    setStr("上传头像");
  };

  return (
    <div style={{ marginLeft: "80px" }}>
      <div style={{ fontSize: "20px", userSelect: 'none', fontWeight: '600' }}>基本信息</div>
      <Row gutter={16}>
        <Col span={14}>
          <Form
            form={form}
            onFinish={updateUserProfile}
            style={{ maxWidth: 600, marginTop: "40px" }}
            labelCol={{ span: 6 }}  // 统一标签宽度
            wrapperCol={{ span: 18 }}  // 统一输入框宽度
          >
            <Form.Item
              name="displayName"
              label="社交昵称"
              rules={[
                {
                  required: true,
                  message: '请输入社交昵称！',
                },
                {
                  pattern: /^.{1,10}$/,
                  message: '用户昵称长度为1-10位!',
                },
                {
                  pattern: /^[\u4e00-\u9fa5A-Za-z0-9]+$/,
                  message: '用户昵称只能包含字母,数字和汉字!',
                },]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="signature"
              label="个性签名"
            >
              <Input placeholder="请输入您的个性签名" />
            </Form.Item>
            <Form.Item
              name="realName"
              label="真实姓名"
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="school"
              label="所在学校"
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="college"
              label="所在学院"
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="class"
              label="所在班级"
            >
              <Input />
            </Form.Item>
            <Form.Item
              style={{ marginLeft: "300px" }} // 将保存按钮对齐到右侧
            >
              <Button type="primary" htmlType="submit">保存</Button>
            </Form.Item>
          </Form>
        </Col>
        <Col span={10} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <Upload
            name="avatar"
            showUploadList={false}
            beforeUpload={beforeUpload}
            maxCount={1}
            fileList={fileList}
          >
            <Avatar style={{ textAlign: "center" }} size={100} src={avatar || "/image/login/defaultFilePath.png"} />
          </Upload>
          <div style={{ textAlign: "center", fontSize: "16px" }}>{str}</div>
          {fileList.length > 0 && (
            <Button onClick={handleRemove} style={{ marginTop: "10px" }}>
              撤销上传
            </Button>
          )}
        </Col>
      </Row>
    </div>

  );
};

export default connect(({ user }) => ({
  userInfo: user.userInfo
}))(PersonalData);
